package com.xbongbong.pro.statistics.help;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.Feature;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.CloneUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.bi.commons.pojo.AggFieldPojo;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.domain.entity.ChartEntity;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.BiErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ChartErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.service.toolbox.statistic.util.ChartResultUtil;
import com.xbongbong.pro.statistic.constant.ChartConstant;
import com.xbongbong.pro.statistic.enums.AdvancedComputingSecondEnum;
import com.xbongbong.pro.statistic.enums.ChartTypeEnum;
import com.xbongbong.pro.statistic.enums.NumFormatEnum;
import com.xbongbong.pro.statistic.enums.RateTypeEnum;
import com.xbongbong.pro.statistic.enums.TimeDimensionEnum;
import com.xbongbong.pro.statistic.help.ChartResultHelp;
import com.xbongbong.pro.statistic.help.FieldAnalysisHelp;
import com.xbongbong.pro.statistic.pojo.ChartFieldAttrPojo;
import com.xbongbong.pro.statistic.pojo.vo.DataWarningQueryListVO;
import com.xbongbong.pro.statistic.pojo.vo.DataWarningQueryVO;
import com.xbongbong.pro.statistic.result.pojo.ChartResultPojo;
import com.xbongbong.pro.statistic.result.pojo.FieldAttrPojo;
import com.xbongbong.pro.statistic.result.pojo.WarningValuePojo;
import com.xbongbong.pro.statistic.result.pojo.vo.ChartAnalysisVO;
import com.xbongbong.pro.statistics.pojo.CkStatisticPojo;
import com.xbongbong.pro.statistics.pojo.dto.ChartAnalysisDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.service.toolbox.help.AttrDecimalPrecisionHelper;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 指标图渲染公有方法
 * @ClassName TargetChartVOHelper
 * @Author 梁鲁江
 * 创建时间 2022/9/26 19:29
 * 修改时间  2022/9/26 19:29
 **/
@Component
public class TargetChartVOHelper {
    @Resource
    private ChartResultHelp chartResultHelp;
    @Resource
    private AttrDecimalPrecisionHelper attrDecimalPrecisionHelper;
    @Resource
    private CkResultHelp ckResultHelp;
    @Resource
    private PaasRedisHelper paasRedisHelper;

    public Logger logger = LoggerFactory.getLogger(getClass());
    
    public ChartAnalysisVO targetChartAnalysis(ChartAnalysisDTO chartAnalysisDTO,Map<String, Map<String, String>> attrLinkMap) throws XbbException {
        ChartAnalysisVO chartAnalysisVO = new ChartAnalysisVO();
        JSONObject result = new JSONObject();
        ChartEntity chartEntity = chartAnalysisDTO.getChartEntity();
        PageHelper pageHelper = chartAnalysisDTO.getPageHelper();
        // 单表or多表数据获取
        JSONArray resultArr = chartAnalysisDTO.getResultArray();
        // 统计值为空直接返回
        if ((CollectionUtils.isEmpty(chartEntity.getSummaryAttr()) || CollectionUtils.isEmpty(resultArr))
                && !Objects.equals(ChartTypeEnum.SECOND_TARGET_CHART.getCode(), chartEntity.getChartType())) {
            result = new JSONObject();
            List list = new ArrayList<>();
            result.put("customTitle", list);
            result.put("customData", list);
            int rowCount = 0;
            result.put("realRowsCount", rowCount);
            pageHelper.setRowsCount(rowCount);
            chartAnalysisVO.setResult(result);
            return chartAnalysisVO;
        }
        Map<String, AggFieldPojo> aggFieldMap = chartAnalysisDTO.getAggFieldMap();
        ChartResultPojo chartResultPojo = chartAnalysisDTO.getChartResultPojo() == null ? new ChartResultPojo() : chartAnalysisDTO.getChartResultPojo();
        Integer pageTurn = chartAnalysisDTO.getPageTurn();
        Boolean exportFlag = chartResultPojo.getExportFlag();
        List<FieldAttrPojo> rowFieldAttrPojoList = JSON.parseArray(chartEntity.getRowGroupAttr().toJSONString(), FieldAttrPojo.class);
        FieldAttrPojo rowGroupAttrPojo = CollectionsUtil.isNotEmpty(rowFieldAttrPojoList) ? rowFieldAttrPojoList.get(0) : null;
        Map<String, FieldAttrPojo> summaryAttrMap = chartAnalysisDTO.getSummaryAttrMap();
        List<FieldAttrPojo> summaryAttrPojoList = JSON.parseArray(chartEntity.getSummaryAttr().toJSONString(), FieldAttrPojo.class);
        FieldAttrPojo summaryAttrPojo = CollectionsUtil.isNotEmpty(summaryAttrPojoList) ? summaryAttrPojoList.get(0) : new FieldAttrPojo();
        JSONArray advancedComputing = summaryAttrPojo.getAdvancedComputing();
        String sumKey = summaryAttrPojo.getAttr() + "&" + summaryAttrPojo.getFieldType();
        // 表头
        List<JSONObject> headList = JSON.parseArray(chartAnalysisDTO.getTableHead().toJSONString(), JSONObject.class);
        result.put("customTitle", headList);
        // 同环比
        boolean isYearChain = chartResultHelp.isYearChain4Date(rowGroupAttrPojo, advancedComputing);
        // 副指标
        List<String> secondTargetKey = chartAnalysisDTO.getSecondTargetKey();
        // 数据总条数
        Integer rowsCount = resultArr.size();
        // 当前页面的数据条数
        int resultData = 0;
        // 总页数
        Integer pageSize = 1;
        // 总计，只有无分组字段才需要
        String totalSum = "";
        // 格式化
        Integer accuracy = summaryAttrPojo.getAccuracy();
        accuracy = accuracy == null ? 0 : accuracy;
        Integer groupingUsed = summaryAttrPojo.getGroupingUsed();
        Integer percentUsed = summaryAttrPojo.getPercentUsed();
        // 使用数值格式
        NumFormatEnum numFormatEnum = NumFormatEnum.getByCode(summaryAttrPojo.getNumFormat());
        Integer numFormat = numFormatEnum.getCode();
        Map<Integer, List<Map<String, CkStatisticPojo>>> pageMap = new LinkedHashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<String, Object> redisMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<Map<String, Object>> curTotalList = new ArrayList<>();
        // 第一次全部查出，后面走redis
        if (!BasicConstant.ONE.equals(pageTurn)) {
            List<Map<String, CkStatisticPojo>> ckStatisticPojoList = new ArrayList<>();
            // key:行分组值，value:统计值
            Map<String, String> groupValueMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            // sql解析
            if (Objects.isNull(rowGroupAttrPojo)) {
                totalSum = parseTargetResultNoRow(resultArr, aggFieldMap, summaryAttrPojo, numFormatEnum);
            } else {
                parseTargetResult(ckStatisticPojoList, resultArr, aggFieldMap, rowGroupAttrPojo, summaryAttrPojo, groupValueMap,chartEntity);
            }
            // 结果解析,无分组字段不需要
            if (CollectionUtils.isNotEmpty(ckStatisticPojoList) && Objects.nonNull(rowGroupAttrPojo)) {
                List<Map<String, CkStatisticPojo>> pageMapList = new ArrayList<>();
                String groupKey = rowGroupAttrPojo.getAttr() + "&" + rowGroupAttrPojo.getFieldType();
                // 解析关联字段
                Map<String, String> parseMap = parseAttrMapForTarget(ckStatisticPojoList, new ArrayList<>(groupValueMap.keySet()), rowGroupAttrPojo, chartAnalysisDTO,attrLinkMap);
                // 解析值
                for (Map<String, CkStatisticPojo> ckStatisticPojoMap : ckStatisticPojoList) {
                    CkStatisticPojo groupStatisticPojo = ckStatisticPojoMap.getOrDefault(groupKey, new CkStatisticPojo());
                    CkStatisticPojo summaryStatisticPojo = ckStatisticPojoMap.getOrDefault(sumKey, new CkStatisticPojo());
                    String groupValue = groupStatisticPojo.getValue();
                    String summaryValue = summaryStatisticPojo.getValue();
                    if (StringUtil.isEmpty(summaryValue) || Objects.equals(summaryValue, StringConstant.SHORT_BARS)) {
                        continue;
                    }
                    // 同环比
                    if (isYearChain) {
                        String oldVal = getOldValue4Target(rowGroupAttrPojo, advancedComputing, Long.valueOf(groupValue), groupValueMap);
                        summaryValue = chartResultHelp.getYearChainValue(summaryAttrPojo, oldVal, summaryValue);
                    }
                    // 关联数据解析
                    String parseValue = chartResultHelp.analysisResultValue(parseMap, groupValue, rowGroupAttrPojo);
                    if (StringUtil.isNotEmpty(parseValue)) {
                        groupStatisticPojo.setValue(parseValue);
                    }
                    // 格式化
                    summaryValue = String.valueOf(ChartResultUtil.formatVal4Num(new BigDecimal(summaryValue), numFormatEnum, FieldAnalysisHelp.isPercentUsedOfAccuracy(percentUsed,accuracy)));
                    summaryValue = attrDecimalPrecisionHelper.getNumberFormat(summaryValue, accuracy, groupingUsed, percentUsed);
                    summaryStatisticPojo.setValue(summaryValue);
                    pageMapList.add(ckStatisticPojoMap);
                    // 副指标用
                    Map<String, Object> valMap = new HashMap<>(1);
                    valMap.put(sumKey, summaryValue);
                    curTotalList.add(valMap);
                    //当前页面的数据条数
                    resultData++;
                    if (resultData >= pageHelper.getPageSize()) {
                        resultData = 0;
                        List<Map<String, CkStatisticPojo>> pageList = new ArrayList<>(pageMapList);
                        pageMapList.clear();
                        Integer index = pageSize++;
                        pageMap.put(index, pageList);
                    }
                }
                // 不够一页的数据
                if (CollectionsUtil.isNotEmpty(pageMapList)) {
                    pageMap.put(pageSize, pageMapList);
                } else {
                    if (pageSize != 1) {
                        pageSize--;
                    }
                }
            }
            redisMap.put("pageMap", pageMap);
            redisMap.put("rowsCount", rowsCount);
            redisMap.put("pageSize", pageSize);
            redisMap.put("totalSum", totalSum);
            //导出时不更新缓存
            if (exportFlag == null || !exportFlag) {
                paasRedisHelper.setValue(RedisPrefixConstant.INDEX_CUSTOM_STATISTIC_RESULT, chartEntity.getCorpid() + "_" + chartEntity.getId(), redisMap, TimeConstant.TINY_DURATION);
            }
        } else {
            String redisResult = paasRedisHelper.getValue(RedisPrefixConstant.INDEX_CUSTOM_STATISTIC_RESULT, chartEntity.getCorpid() + "_" + chartEntity.getId());
            if (StringUtil.isNotEmpty(redisResult)) {
                redisMap = JSONObject.parseObject(redisResult, Feature.OrderedField);
                pageMap = JSON.parseObject(redisMap.get("pageMap").toString(), new TypeReference<Map<Integer, List<Map<String, CkStatisticPojo>>>>() {
                }, Feature.OrderedField);
                rowsCount = (Integer) redisMap.get("rowsCount");
                pageSize = (Integer) redisMap.get("pageSize");
                totalSum = String.valueOf(redisMap.get("totalSum"));
            } else {
                targetChartAnalysis(chartAnalysisDTO,attrLinkMap);
            }
        }
        if ("".equals(totalSum) && Objects.isNull(rowGroupAttrPojo)) {
            logger.error(BiErrorCodeEnum.API_ERROR_241019.getMsg());
            throw new XbbException(BiErrorCodeEnum.API_ERROR_241019);
        }
        List<Map<String, CkStatisticPojo>> resultPage = pageMap.get(pageHelper.getCurrentPageNum());
        if (resultPage == null) {
            resultPage = new ArrayList<>();
        }
        result.put("customData", resultPage);
        result.put("totalSum", totalSum);
        // 副指标
        packageSecondValue(chartEntity,secondTargetKey,rowFieldAttrPojoList,resultPage,curTotalList,sumKey,summaryAttrMap,result,summaryAttrPojo);
        result.put("customTotal", curTotalList);
        if (rowsCount > ChartConstant.MAX_SIZE) {
            rowsCount = ChartConstant.MAX_SIZE;
        }
        result.put("realRowsCount", rowsCount);
        pageHelper.setRowsCount(rowsCount);
        pageHelper.setPageTotal(pageSize);
        // 指标图数据预警处理，副指标暂无
        if (Objects.equals(chartEntity.getChartType(), ChartTypeEnum.TARGET_CHART.getCode())) {
            handleDW(chartAnalysisDTO, result, chartEntity, pageHelper, pageMap, totalSum);
        }
        chartAnalysisVO.setResult(result);
        return chartAnalysisVO;
    }


    /**
     * 指标图结果获取（有分组）
     * @param ckStatisticPojoList 处理完的结果数据集
     * @param resultArr ck原结果数据集
     * @param aggFieldMap ck统计值映射map
     * @param rowGroupAttrPojo 分组字段pojo
     * @param summaryAttrPojo 统计值pojo
     * @param groupValueMap key:行分组值，value:统计值
     * @author xinpeng.jiang
     * @date 2021/11/19 16:38
     * @version 1.0
     */
    private void parseTargetResult(List<Map<String, CkStatisticPojo>> ckStatisticPojoList, JSONArray resultArr, Map<String, AggFieldPojo> aggFieldMap,
                                   FieldAttrPojo rowGroupAttrPojo, FieldAttrPojo summaryAttrPojo, Map<String, String> groupValueMap,ChartEntity chartEntity) {
        if (CollectionUtils.isEmpty(resultArr) || Objects.isNull(summaryAttrPojo) || Objects.isNull(rowGroupAttrPojo)) {
            return;
        }
        String rowGroupAttr = rowGroupAttrPojo.getAttr();
        String summaryAttr = summaryAttrPojo.getAttr();
        Integer rowGroupFieldType = rowGroupAttrPojo.getFieldType();
        Integer summaryFieldType = summaryAttrPojo.getFieldType();
        int teamIdx = EsUtil.getTeamIdx(chartEntity, rowGroupAttrPojo.getFormId());
        for (int i = 0; i < resultArr.size(); i++) {
            JSONObject resultObj = resultArr.getJSONObject(i);
            // 分组字段
            String groupValue;
            if(EsHelper.isTeamLogicByFieldType(rowGroupFieldType, rowGroupAttrPojo.getBusinessType())) {
                groupValue =  ckResultHelp.getTeamValue(rowGroupFieldType, teamIdx, resultObj).toString();
            }else if(Objects.equals(FieldTypeEnum.ADDRESS.getType(),rowGroupFieldType) || Objects.equals(FieldTypeEnum.LOCATION.getType(),rowGroupFieldType)){
                groupValue = FastJsonHelper.getStringOrDefault(resultObj, rowGroupAttr.replaceAll("\\.","_"), "");
            } else {
                groupValue = FastJsonHelper.getStringOrDefault(resultObj, rowGroupAttr, "");
                // 处理毫秒数
                groupValue = ckResultHelp.handleDate2Ms(rowGroupFieldType, groupValue);
            }
            CkStatisticPojo groupPojo = new CkStatisticPojo(rowGroupAttr, rowGroupAttr + "&" + rowGroupFieldType, groupValue, groupValue);
            // 获取统计结果
            for (Map.Entry<String, AggFieldPojo> aggFieldPojoEntry : aggFieldMap.entrySet()) {
                AggFieldPojo aggFieldPojo = aggFieldPojoEntry.getValue();
                String originAttr = aggFieldPojo.getAttr();
                String aggAttr = aggFieldPojoEntry.getKey();
                CkStatisticPojo summaryPojo = new CkStatisticPojo();
                if (Objects.equals(originAttr, summaryAttr)) {
                    // 统计值
                    String summaryValue = FastJsonHelper.getStringOrDefault(resultObj, aggAttr, "");
                    summaryPojo = new CkStatisticPojo(summaryAttr, summaryAttr + "&" + summaryFieldType, summaryValue, summaryValue);
                    groupValueMap.put(groupValue, summaryValue);
                }
                // 放入
                LinkedHashMap<String, CkStatisticPojo> resultMap = new LinkedHashMap<>(2);
                resultMap.put(groupPojo.getKey(), groupPojo);
                resultMap.put(summaryPojo.getKey(), summaryPojo);
                ckStatisticPojoList.add(resultMap);
            }
        }
    }

    /**
     * 指标图结果获取（无分组）
     * @param resultArr ck原结果数据集
     * @param aggFieldMap ck统计值映射map
     * @param summaryAttrPojo 统计值pojo
     * @param numFormatEnum 数值格式
     * @return java.lang.String 总计
     * @author xinpeng.jiang
     * @date 2021/11/19 16:38
     * @version 1.0
     */
    private String parseTargetResultNoRow(JSONArray resultArr, Map<String, AggFieldPojo> aggFieldMap, FieldAttrPojo summaryAttrPojo, NumFormatEnum numFormatEnum) {
        if (CollectionUtils.isEmpty(resultArr) || Objects.isNull(summaryAttrPojo)) {
            return "";
        }
        BigDecimal totalSum = new BigDecimal("0");
        String summaryAttr = summaryAttrPojo.getAttr();
        for (int i = 0; i < resultArr.size(); i++) {
            JSONObject resultObj = resultArr.getJSONObject(i);
            // 获取统计结果
            for (Map.Entry<String, AggFieldPojo> aggFieldPojoEntry : aggFieldMap.entrySet()) {
                AggFieldPojo aggFieldPojo = aggFieldPojoEntry.getValue();
                String originAttr = aggFieldPojo.getAttr();
                String aggAttr = aggFieldPojoEntry.getKey();
                if (Objects.equals(originAttr, summaryAttr)) {
                    // 统计值
                    String summaryValue = FastJsonHelper.getStringOrDefault(resultObj, aggAttr, "0");
                    totalSum = totalSum.add(new BigDecimal(summaryValue));
                }
            }
        }
        // 小数精度
        int accuracy = summaryAttrPojo.getAccuracy() == null ? 0 : summaryAttrPojo.getAccuracy();
        // 是否使用百分比
        Integer percentUsed = summaryAttrPojo.getPercentUsed() == null ? 0 : summaryAttrPojo.getPercentUsed();
        // 是否使用千分符
        Integer groupingUsed = summaryAttrPojo.getGroupingUsed() == null ? summaryAttrPojo.getAmountFlag() : summaryAttrPojo.getGroupingUsed();
        // 是否使用数值格式
        totalSum = ChartResultUtil.formatVal4Num(totalSum, numFormatEnum);
        // 格式化
        return attrDecimalPrecisionHelper.getNumberFormat(String.valueOf(totalSum), accuracy, groupingUsed, percentUsed);
    }

    /**
     * 指标图数据预警处理
     * @param chartAnalysisDTO
     * @param result
     * @param chartEntity
     * @param pageHelper
     * @param pageMap
     * @param totalSum
     * @throws XbbException
     * @author mengna.deng
     * @date 2021/11/12 10:53
     * @version 1.0
     */
    private void handleDW(ChartAnalysisDTO chartAnalysisDTO, JSONObject result, ChartEntity chartEntity, PageHelper pageHelper, Map<Integer, List<Map<String, CkStatisticPojo>>> pageMap, String totalSum) throws XbbException {
        Map<String, Object> dwVoMap = chartResultHelp.getDWQueryListVO(chartAnalysisDTO, chartEntity);
        DataWarningQueryListVO dataWarningQueryListVO = (DataWarningQueryListVO) dwVoMap.get("dataWarningQueryListVO");
        String key = (String) dwVoMap.get("key");
        String rowAttr = "";
        if (null != chartEntity && CollectionUtils.isNotEmpty(chartEntity.getRowGroupAttr())) {
            FieldAttrPojo fieldAttrPojo2 = chartEntity.getRowGroupAttr().getJSONObject(0).toJavaObject(FieldAttrPojo.class);
            rowAttr = fieldAttrPojo2.getAttr() + "&" + fieldAttrPojo2.getFieldType();
        }
        // 为了防止一个当前预警数据同时触发多个预警设置，不知道选那个，取这个预警数据到预警设置最接近的数据
        Map<String, Object> distinctMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<WarningValuePojo> warningValues = new ArrayList<>();
        // 预警的接口
        int warningIndex = 0;
        if (Objects.nonNull(dataWarningQueryListVO) && CollectionUtils.isNotEmpty(dataWarningQueryListVO.getDataWarningQueryVOList()) && Objects.nonNull(pageMap) && pageMap.size() > 0) {
            for (DataWarningQueryVO item : dataWarningQueryListVO.getDataWarningQueryVOList()) {
                int valueIndex = 0;
                for (Map<String, CkStatisticPojo> stringObjectMap : pageMap.get(pageHelper.getCurrentPageNum())) {
                    if (chartResultHelp.checkIsTrigger(item.getTriggerCondition(), String.valueOf(stringObjectMap.get(key).getValue()))) {
                        WarningValuePojo pojo = new WarningValuePojo();
                        pojo.setRowValue(String.valueOf(stringObjectMap.get(rowAttr).getValue()));
                        pojo.setWarningFlag(true);
                        pojo.setValue(String.valueOf(stringObjectMap.get(key).getValue()));
                        pojo.setColor(item.getColor());
                        if (chartResultHelp.isCover(item.getTriggerCondition(), String.valueOf(stringObjectMap.get(key).getValue()), distinctMap, valueIndex)) {
                            if ((warningValues.size() - 1) >= valueIndex) {
                                warningValues.set(valueIndex, pojo);
                            } else {
                                warningValues.add(pojo);
                            }
                        } else if (warningValues.size() < pageMap.get(pageHelper.getCurrentPageNum()).size()) {
                            warningValues.add(pojo);
                        }
                    } else if (warningIndex == 0) {
                        WarningValuePojo pojo = new WarningValuePojo();
                        pojo.setRowValue(String.valueOf(stringObjectMap.get(rowAttr).getValue()));
                        pojo.setWarningFlag(false);
                        pojo.setValue(String.valueOf(stringObjectMap.get(key).getValue()));
                        warningValues.add(pojo);
                    }
                    valueIndex++;
                }
                warningIndex++;
            }
        } else if (StringUtil.isNotEmpty(totalSum)) {
            for (DataWarningQueryVO item : dataWarningQueryListVO.getDataWarningQueryVOList()) {
                int valueIndex = 0;
                if (chartResultHelp.checkIsTrigger(item.getTriggerCondition(), totalSum)) {
                    WarningValuePojo pojo = new WarningValuePojo();
                    pojo.setWarningFlag(true);
                    pojo.setValue(totalSum);
                    pojo.setColor(item.getColor());
                    if (chartResultHelp.isCover(item.getTriggerCondition(), totalSum, distinctMap, valueIndex)) {
                        if ((warningValues.size() - 1) >= valueIndex) {
                            warningValues.set(valueIndex, pojo);
                        } else {
                            warningValues.add(pojo);
                        }
                    } else if (warningValues.size() < 1) {
                        warningValues.add(pojo);
                    }
                } else if (warningIndex == 0) {
                    WarningValuePojo pojo = new WarningValuePojo();
                    pojo.setWarningFlag(false);
                    pojo.setValue(totalSum);
                    warningValues.add(pojo);
                }
                warningIndex++;
            }
        }
        result.put("warningValues", warningValues);
    }

    /**
     * 获取同环比差值-指标图
     * @param rowGroupAttrPojo 分组字段
     * @param advancedComputing 高级计算
     * @param nowTimestamp 当前值时间戳
     * @param groupValueMap key:行分组值，value:统计值
     * @return java.lang.String
     * @author xinpeng.jiang
     * @date 2021/11/25 10:46
     * @version 1.0
     */
    private String getOldValue4Target(FieldAttrPojo rowGroupAttrPojo, JSONArray advancedComputing, Long nowTimestamp, Map<String, String> groupValueMap) {
        // 计算差值时间戳
        Long oldTimestamp = ckResultHelp.getYearChainDiff(rowGroupAttrPojo, advancedComputing, nowTimestamp);
        // 去map中拿旧值，拿不到就是0
        String oldVal = groupValueMap.get(oldTimestamp.toString());
        return oldVal == null ? "0" : oldVal;
    }



    /**
     * 指标图关联数据解析
     * @param resultList 原结果集
     * @param valueList 统计值list
     * @param rowGroupAttrPojo 分组字段
     * @param chartAnalysisDTO dto
     * @return java.util.Map<java.lang.String, java.lang.String>
     * @author xinpeng.jiang
     * @date 2021/11/24 11:06
     * @version 1.0
     */
    public Map<String, String> parseAttrMapForTarget(List<Map<String, CkStatisticPojo>> resultList, List<String> valueList, FieldAttrPojo rowGroupAttrPojo, ChartAnalysisDTO chartAnalysisDTO,Map<String, Map<String, String>> attrLinkMap) {
        if (resultList == null || valueList == null) {
            return null;
        }
        Map<String, String> parseMap = null;
        try {
            parseMap = ckResultHelp.valueListAnalysis(rowGroupAttrPojo, chartAnalysisDTO.getCorpid(), valueList, chartAnalysisDTO.getChartEntity(), true, null, true, chartAnalysisDTO, null,attrLinkMap);
        } catch (XbbException e) {
            logger.error("指标图解析联动数据、下拉框出错", e);
        }
        if (parseMap != null) {
            Integer fieldType = rowGroupAttrPojo.getFieldType();
            if (Objects.equals(fieldType, FieldTypeEnum.LINK_BUSINESS_SINGLE.getType()) || Objects.equals(fieldType, FieldTypeEnum.LINK_BUSINESS_MULTI.getType())) {
                parseMap = chartResultHelp.parseLinkBusinessMap(parseMap);
            }
        }
        return parseMap;
    }

    /**
     * 封装副指标图
     * @param chartEntity
     * @param secondTargetKey
     * @param rowFieldAttrPojoList
     * @param resultPage
     * @param curTotalList
     * @param sumKey
     * @param summaryAttrMap
     * @param result
     * @throws XbbException
     */
    private void packageSecondValue(ChartEntity chartEntity,List<String> secondTargetKey,List<FieldAttrPojo> rowFieldAttrPojoList,List<Map<String, CkStatisticPojo>> resultPage,
                                    List<Map<String, Object>> curTotalList,String sumKey,Map<String, FieldAttrPojo> summaryAttrMap,JSONObject result,FieldAttrPojo summaryAttrPojo) throws XbbException {
        // 是主副指标，且高级计算不为无
        if (Objects.equals(chartEntity.getChartType(),ChartTypeEnum.SECOND_TARGET_CHART.getCode()) && CollectionUtils.isNotEmpty(secondTargetKey) && secondTargetKey.size()>1){
            if (CollectionUtils.isNotEmpty(rowFieldAttrPojoList)){
                // 中英文，获取要拼接的前缀和后缀
                Boolean englishFlag = Objects.equals(LocaleContextHolder.getLocale().getLanguage(), I18nStringConstant.ENGLISH_LANGUAGE);
                List<FieldAttrPojo> secondTargetList;
                if(CollectionUtils.isNotEmpty(chartEntity.getSecondTargetAttr())){
                    secondTargetList = JSONArray.parseArray(chartEntity.getSecondTargetAttr().toJSONString(), FieldAttrPojo.class);
                }else {
                    throw new XbbException(ChartErrorCodeEnum.API_ERROR_310001);
                }
                FieldAttrPojo fieldAttrPojo = secondTargetList.get(0);
                JSONArray advancedComputing = fieldAttrPojo.getAdvancedComputing();
                String timeDimension = secondTargetList.get(0).getTimeDimension();
                TimeDimensionEnum timeDimensionEnum = TimeDimensionEnum.getByFormatStr(timeDimension);
                String ratePrefix = I18nMessageUtil.getMessage(I18nStringConstant.LAST) + timeDimensionEnum.getName();
                String rateSuffix = I18nMessageUtil.getMessage(I18nStringConstant.YEAR_ON_YEAR);
                if (englishFlag){
                    ratePrefix = I18nMessageUtil.getMessage(I18nStringConstant.LAST) + " " + timeDimensionEnum.getName() + " ";
                }

                // 获取之前和现在的两个值
                String rowKey = rowFieldAttrPojoList.get(0).getAttr() + "&" + rowFieldAttrPojoList.get(0).getFieldType();
                int index = 0;
                List<Map<String, Object>> secondCustomTotal = new ArrayList<>();
                List<Map<String, Object>> curTotalListTemp = (List<Map<String, Object>>) CloneUtil.deepClone(curTotalList);;
                Iterator<Map<String, CkStatisticPojo>> iterator = resultPage.iterator();
                String curValue = "0";
                String lastValue = "0";
                while(iterator.hasNext()){
                    Map<String, CkStatisticPojo> item = iterator.next();
                    CkStatisticPojo rowPojo = item.get(rowKey);
                    if (Objects.nonNull(rowPojo) && Objects.equals(rowPojo.getOriginValue(), secondTargetKey.get(0))) {
                        if (index < curTotalList.size()){
                            secondCustomTotal.add(curTotalList.get(index));
                            lastValue = String.valueOf(curTotalList.get(index).get(sumKey));
                            curTotalListTemp.remove(index);
                        }
                    }else if (Objects.nonNull(rowPojo) && Objects.equals(rowPojo.getOriginValue(), secondTargetKey.get(1))){
                        curValue = String.valueOf(curTotalList.get(index).get(sumKey));
                    }
                    index ++;
                }
                curTotalList = curTotalListTemp;
                // 赋默认值0
                if (CollectionUtils.isEmpty(curTotalList)){
                    Map<String,Object> curTotalMap = new HashMap<String,Object>(){{put(sumKey,0);}};
                    chartResultHelp.formatAggData(summaryAttrMap, curTotalMap);
                    curTotalList.add(curTotalMap);

                }
                if (CollectionUtils.isEmpty(secondCustomTotal)){
                    Map<String,Object> secondTotalMap = new HashMap<String,Object>(){{put(sumKey,0);}};
                    chartResultHelp.formatAggData(summaryAttrMap, secondTotalMap);
                    secondCustomTotal.add(secondTotalMap);
                }
                curTotalList.addAll(secondCustomTotal);
                String rate;
                curValue = chartResultHelp.reverseFieldAttrPojoFormat(summaryAttrPojo,curValue);
                lastValue = chartResultHelp.reverseFieldAttrPojoFormat(summaryAttrPojo,lastValue);
                Float curFloatValue = Float.parseFloat(curValue);
                Float lastFloatValue = Float.parseFloat(lastValue);
                // 增长、下降或者持平
                if (curFloatValue.compareTo(lastFloatValue) == 0){
                    result.put(StringConstant.RATE_TYPE, RateTypeEnum.INVARIANT.getCode());
                }else if (curFloatValue.compareTo(lastFloatValue) > 0){
                    result.put(StringConstant.RATE_TYPE, RateTypeEnum.INCREASE.getCode());
                }else {
                    result.put(StringConstant.RATE_TYPE, RateTypeEnum.DECREASE.getCode());
                }
                // 求rate值
                boolean isYearChain = chartResultHelp.isYearChain4Subtitle(advancedComputing);
                if (isYearChain){
                    String advancedComputingSecond = advancedComputing.getString(1);
                    AdvancedComputingSecondEnum advancedComputingSecondEnum = AdvancedComputingSecondEnum.getByAlias(advancedComputingSecond);
                    Float diffFloat = curFloatValue - lastFloatValue;
                    switch (advancedComputingSecondEnum){
                        case YEAR_VALUE:
                        case CHAIN_VALUE:
                            rate = String.valueOf(Math.abs(diffFloat.floatValue()));
                            break;
                        case YEAR_RATE:
                        case CHAIN_RATE:
                            if (lastFloatValue.compareTo(0.0f) == 0){
                                if (diffFloat.compareTo(0.0f) == 0){
                                    rate = "0";
                                }else{
                                    rate = "1";
                                }
                            }else {
                                rate = String.valueOf(Math.abs(diffFloat/lastFloatValue));
                            }
                            break;
                        default:
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                    }
                    // 是否环比
                    boolean isChain = Objects.equals(AdvancedComputingSecondEnum.getYearOrChain(advancedComputing.getString(1)),2);
                    if (isChain){
                        rateSuffix = I18nMessageUtil.getMessage(I18nStringConstant.SEQUENTIAL);
                    }
                }else {
                    // 默认环比增长值
                    rate = String.valueOf(Math.abs(curFloatValue-lastFloatValue));
                }
                curValue = fieldAttrPojoFormat(summaryAttrPojo,curValue);
                lastValue = fieldAttrPojoFormat(summaryAttrPojo,lastValue);
                rate = fieldAttrPojoFormat(fieldAttrPojo,rate);
                result.put("rateTitle",ratePrefix + rateSuffix);
                result.put("totalSum",curValue);
                result.put("secondTotalSum",lastValue);
                result.put("rate", rate);
            }
        }
    }

    /**
     * 字段 数字数据格式化
     *
     */
    private String fieldAttrPojoFormat(FieldAttrPojo fieldAttrPojo, String num) {
        if (Objects.isNull(fieldAttrPojo) || StringUtil.isEmpty(num) || Objects.equals(num, StringConstant.SHORT_BARS)) {
            return num;
        }
        Integer accuracy = fieldAttrPojo.getAccuracy();
        accuracy = accuracy == null ? 0 : accuracy;
        Integer percentUsed = fieldAttrPojo.getPercentUsed();
        Integer groupingUsed = fieldAttrPojo.getGroupingUsed() == null ? fieldAttrPojo.getAmountFlag() : fieldAttrPojo.getGroupingUsed();
        // 使用数值格式
        Integer numFormat = fieldAttrPojo.getNumFormat();
        NumFormatEnum numFormatEnum = NumFormatEnum.getByCode(numFormat);
        String newVal = String.valueOf(ChartResultUtil.formatVal4Num(new BigDecimal(num), numFormatEnum, accuracy));
        return attrDecimalPrecisionHelper.getNumberFormat(newVal, accuracy, groupingUsed, percentUsed);
    }

}
